import React, {Component}       from 'react';
import {connect}                from 'react-redux';
import {Field, reduxForm, initialize, change, formValueSelector}     from 'redux-form';
import Button                   from '../components/Button';
import Modal                    from '../components/Modal';
import Avatar                   from '../components/Avatar';
import FileInput                from '../components/FileInput';
import Form                     from '../components/Form';
import api                      from '../../api';
import {fetchCurrentFromServer} from '../../actions/user'

const selector = formValueSelector('profileForm');

@reduxForm({
	form: 'profileForm',  // a unique identifier for this form
	validate(values) {
		const errors = {};
		if (!values.nickname) errors.nickname = '必填字段';
		if (!values.gender) errors.gender = '必填字段';
		if ([-1, 0, 1].indexOf(parseInt(values.gender)) < 0) errors.gender = "选项不正确";
		return errors
	}                // <--- validation function given to redux-form
})
class Profile extends Component {

	componentDidMount() {
		api.getProfile().then((data) => this.props.initialize(Object.assign(data, {gender: data.gender + ''}), true, "profileForm"));
	}

	handleSubmit(values) {
		api.putProfile(Object.assign({}, values, {gender: parseInt(values.gender)})).then((data) => {
			Modal.message.info("更新成功");
			this.props.fetchCurrentFromServer();
		});
	}

	handleAvatarChange(url) {
		this.props.change('avatar', url);
	}


	render() {
		// avatar, nickname, gender, location, signature
		const {handleSubmit, avatarValue} = this.props;
		return (
			<Form className="form" onSubmit={handleSubmit(this.handleSubmit.bind(this)) }>
				<div className="form-field">
					<label>头像</label>
					<div className="form-field-wrapper">
						{avatarValue && <div><Avatar size={80} src={avatarValue}/></div>}

						<FileInput accept="image/*" onChange={this.handleAvatarChange.bind(this)}>上传头像</FileInput>
					</div>
				</div>
				<Field name="nickname" type="text" component={Form.renderInputField} label="昵称"/>
				<Field name="gender" component={Form.renderRadioField } label="性别"
				       items={[['0', '女'], ['1', "男"], ['-1', '保密']]}/>
				<Field name="signature" type="textarea" component={Form.renderTextField} label="签名"/>

				<div className="form-field">
					<label/>
					<div className="form-field-wrapper">
						<Button type="submit">提交</Button>
					</div>
				</div>
			</Form>
		);
	}
}

export default connect(
	function (state, props) {
		const avatarValue = selector(state, 'avatar');
		return {
			pristine: state.user.profile._id,
			initialValues: state.user.profile,
			avatarValue: avatarValue
		};
	},
	{initialize, fetchCurrentFromServer}
)(Profile);
